package org.itboys.mobile.service.mysql.mobile;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dao.TianJieGroupRecordMapper;
import org.itboys.mobile.dao.TianJieWalletProductMapper;
import org.itboys.mobile.dao.TianJieWalletRecordMapper;
import org.itboys.mobile.dao.TianJieWalletReleaseRecordMapper;
import org.itboys.mobile.dto.TianJieWalletDto;
import org.itboys.mobile.dto.TianJieWalletProductDto;
import org.itboys.mobile.dto.TianJieWalletRecordDto;
import org.itboys.mobile.entity.mongo.TianJieFinanceAccount;
import org.itboys.mobile.entity.mongo.TianJieMember;
import org.itboys.mobile.entity.mysql.*;
import org.itboys.mobile.service.mongo.mobile.TianJieMobileAccountService;
import org.itboys.mobile.service.mongo.mobile.TianJieMobileMemberService;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：天街_消费卡_service
 */
@Service
public class TianJieMobileWalletService extends BaseMySqlService<TianJieWallet> {
    @Autowired
    private TianJieWalletRecordMapper walletRecordMapper;
    @Autowired
    private TianJieWalletProductMapper walletProductMapper;
    @Autowired
    private TianJieMobileMemberService memberService;
    @Autowired
    private TianJieMobileWalletBlockService walletBlockService;
/*    @Autowired
    private TianJieMobileGroupService groupService;
    @Autowired
    private TianJieGroupRecordMapper groupRecordMapper */;
    @Autowired
    private TianJieMobileAccountService accountService;
    @Autowired
    private TianJieWalletReleaseRecordMapper releaseRecordMapper;
    /**
     * 查找用户消费卡主体
     * @param memberId

     * @return
     */
    @Transactional
    public TianJieWalletDto getWallet(Long memberId,Boolean isCheckRevenue){
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("memberId", memberId);
        TianJieWallet wallet=null;
        List<TianJieWallet> wallets=super.select(param);
        if(ListUtil.isNotNull(wallets)){
            wallet=wallets.get(0);
        }else {
            wallet=new TianJieWallet(memberId);
            super.insert(wallet);
            wallet=super.find(wallet.getId());
        }
        return packageDtoSingle(wallet,isCheckRevenue);
    }

    /**
     * 通过用户寻找消费卡钱包
     * @param memberId
     * @return
     */
    @Transactional
    public TianJieWallet findByMemberId(Long memberId ){
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("memberId", memberId);
        TianJieWallet wallet=null;
        List<TianJieWallet> wallets=super.select(param);
        if(ListUtil.isNotNull(wallets)){
            wallet=wallets.get(0);
        }else {
            wallet=new TianJieWallet(memberId);
            super.insert(wallet);
            wallet=super.find(wallet.getId());
        }
        return wallet;
    }
    /**
     * 获取消费卡（钱包消费记录）
     */
    public List<TianJieWalletRecordDto> getRecord(HttpServletRequest request,Long memberId,Integer type){
        Map<String,Object> param = ParamUtil.packageMysqlPageParam(request,"");
        param.put("status", SundayCommonConstants.YES);
        param.put("memberId",memberId);
        if(type!=null){
            param.put("type",type);
        }
     //   List<TianJieWalletRecord> records=
        return packageRecordDtoMuilt(walletRecordMapper.select(param));
    }

    /**

    *
     * 拨付。团队领导人将自己的消费卡余额，驳回给团队成员
     * @param memberId

     * @param amount
    @Transactional
    public void present(Long memberId,Long partnerId,BigDecimal amount){
        //校验是否是队长
        TianJieMember member = memberService.getById(memberId);
        if(member.getFinanceIsCaptain()!=SundayCommonConstants.YES){
            throw new ErrorException("您不是队长，无法拨付");
        }

        //获取团队可用金额
        TianJieGroup group =groupService.find(member.getFinanceGroupId());
        if(amount.compareTo(group.getPresentAmount())==1){
            throw new ErrorException("团队可用拨付金额不足，请重试");
        }
        //扣减团队的可用拨付金额
        group.setPresentAmount(group.getPresentAmount().subtract(amount));
        groupService.update(group);
        //生成团队拨付记录
        TianJieMember partner = memberService.getById(partnerId);
        groupRecordMapper.insert( new TianJieGroupRecord(group.getId(), partnerId, partner.getNickName(),  amount,SundayCommonConstants.group_record_type_captain));
        //增加队员的可用金额
        generateRecord(null,partnerId, amount,SundayCommonConstants.wallet_record_type_present,"团队拨付",0l);
      //  generateRecord(wallet,partnerId, amount,SundayCommonConstants.wallet_record_type_present_receive,"来至团队的拨付",0l);
    }

    /**
     * 托管到区块链。
     * @param memberId
     * @param amount
     */
    public void deposit(Long memberId,BigDecimal amount){
        TianJieWallet wallet= findByMemberId(memberId);
        BigDecimal unreleaseAmount =wallet.getUnreleaseAmount();
        if(amount.compareTo(unreleaseAmount)==1){
            throw new ErrorException("消费卡待释放余额不足，请重试");
        }
        generateRecord(wallet,memberId, amount,SundayCommonConstants.wallet_record_type_deposit,"托管到区块链",0l);
    }


    /**
     * 获取充值产品
     */
    public List<TianJieWalletProductDto> getProducts(Integer type){
        Map<String,Object> param =new HashMap<String,Object>();
        param.put("type",type);
        return packageProductDtoMuilt(walletProductMapper.select(param));
    }

    /**
     * 申请提现
     * @param memberId
     * @param bitAddress
     * @param amount
     */
    @Transactional
    public  void applyCash(long memberId,String bitAddress,BigDecimal amount){
        TianJieWallet  wallet=findByMemberId(memberId);
        //提现扣减顺序。日薪-周薪-理财
        BigDecimal ableCashAmount = wallet.getCashAmount().add(wallet.getReleaseAmount()).add(wallet.getProfitAmount());
        if(amount.compareTo(ableCashAmount)==1){
            throw new ErrorException("当前最大提现金额为:"+amount);
        }
        //本次变动钱包已释放金额。周薪
        BigDecimal thisReleaseAmount =null;
        //本次变动钱包现金金额。日薪
        BigDecimal thisCashAmount = null;
        //本次变动钱包区块链收益金额。理财收益
        BigDecimal thisProfitAmount = null;
        BigDecimal negativeOne=new BigDecimal("-1");//-1
        //开始按扣减顺序扣减。日薪-周薪-理财 1540.950 0 0
        //1,扣日薪
        if(wallet.getCashAmount().compareTo(amount)!=-1){
            thisCashAmount=amount;
        }else{
            thisCashAmount=wallet.getCashAmount();
            //2,扣周薪
            if(wallet.getReleaseAmount().compareTo(amount.subtract(thisCashAmount))!=-1){
                thisReleaseAmount=amount.subtract(thisCashAmount);
            }else{
                thisReleaseAmount=wallet.getReleaseAmount();
                //2017年12月14日，提币不计算理财
               /* //3,扣理财
                if(wallet.getProfitAmount().compareTo(amount.subtract(thisCashAmount).subtract(thisReleaseAmount))!=-1){
                    thisProfitAmount=amount.subtract(thisCashAmount).subtract(thisReleaseAmount);
                }else{
                    thisProfitAmount=wallet.getProfitAmount();
                }*/
            }
        }
       /* if(1==1){
            return ;
        }*/
        //生成提现记录
        amount=amount.multiply(negativeOne);
        TianJieWalletRecord walletRecord = new TianJieWalletRecord(memberId, wallet.getId(), SundayCommonConstants.wallet_record_type_cash, "提现申请中", ableCashAmount, amount, SundayCommonConstants.YES);

        //设置提现相关属性
      // TianJieFinanceAccount account=accountService.getById(accountId);
        //walletRecord.setAccountId(accountId);
       /* walletRecord.setAccountName(account.getBtAccount());
        walletRecord.setAccountBank(account.getBankName());*/
        walletRecord.setAccountNo(bitAddress);
        walletRecord.setAccountStatus(SundayCommonConstants.wallet_record_cash_status_apply);
        //2017年12月16日增加，换算成比特币价格和数量
        BigDecimal bitcoinPrice=walletBlockService.getMarketPrice(0l,1);
        BigDecimal bitcoinNumber = amount.multiply(negativeOne).divide(bitcoinPrice,2,BigDecimal.ROUND_HALF_UP);
        walletRecord.setAccountBitcoinPrice(bitcoinPrice);
        walletRecord.setAccountBitcoinNumber(bitcoinNumber);
        //修改钱包主体
        logger.info("--thisCashAmount-="+thisCashAmount+",thisReleaseAmount="+thisReleaseAmount+",thisProfitAmount="+thisProfitAmount);

        walletRecord.setAccountCashAmount(thisCashAmount);
        walletRecord.setAccountReleaseAmount(thisReleaseAmount);
        walletRecord.setAccountProfitAmount(thisProfitAmount);
        walletRecordMapper.insert(walletRecord);
        if(thisCashAmount!=null){
            wallet.setCashAmount(wallet.getCashAmount().subtract(thisCashAmount));
        }
        if(thisReleaseAmount!=null){
            wallet.setReleaseAmount(wallet.getReleaseAmount().subtract(thisReleaseAmount));
        }
        if(thisProfitAmount!=null){
            wallet.setCashAmount(wallet.getProfitAmount().subtract(thisProfitAmount));
        }
        super.update(wallet);

    }





    /**
     * 生成消费卡记录
     * @param memberId
     * @param amount
     * @param type
     *
     * 包含以下操作
     * 1，充值，2拨付(8个月返还)
     * 3，托管区块链（解冻金额）4，退出区块链,返还本金，4个月返还；5，退出区块链,返还收益,可立即提现）
     * 6，推荐用户充值（可立即提现）
     * 7，游戏充值。直接扣减待释放
     * 8，释放待释放金额。（可立即提现）
     *
     */
    @Transactional
    public Long generateRecord(TianJieWallet wallet, Long memberId, BigDecimal amount, Integer type, String remark, Long recordId){

             if(wallet==null){
                 wallet=findByMemberId(memberId);
             }

            // boolean isChangeWallet=true;//是否修改钱包
            // boolean isGenerateReleaseRecord=false;//是否生成释放计划
             BigDecimal negativeOne=new BigDecimal("-1");//-1
            //本次变动钱包总额
             BigDecimal thisTotalAmount =new BigDecimal("0");
            //本次变动钱包待释放金额
            BigDecimal thisUnreleaseAmount =new BigDecimal("0");
            //本次变动的冻结金额
            BigDecimal thisFrozenAmount = new BigDecimal("0");
            /**以下是可提现金额**/
            //本次变动钱包已释放金额。
            BigDecimal thisReleaseAmount =new BigDecimal("0");
            //本次变动钱包现金金额
            BigDecimal thisCashAmount = new BigDecimal("0");
            //本次变动钱包已释放金额
            BigDecimal thisProfitAmount =new BigDecimal("0");




            /**
             * 游戏充值 减
             */
             if(type==SundayCommonConstants.wallet_record_type_game){
                amount=amount.multiply(negativeOne);
                TianJieWalletRecord walletRecord=new TianJieWalletRecord( memberId,  wallet.getId(), type, remark, wallet.getUnreleaseAmount(),amount, SundayCommonConstants.YES);
                walletRecordMapper.insert(walletRecord);
                //变更钱包主体信息
                thisUnreleaseAmount=amount;

            /**
             * 托管区块链 减
             */
            }else if(type==SundayCommonConstants.wallet_record_type_deposit) {
                amount = amount.multiply(negativeOne);
                TianJieWalletRecord walletRecord = new TianJieWalletRecord(memberId, wallet.getId(), type, remark, wallet.getUnreleaseAmount(), amount, SundayCommonConstants.YES);
                walletRecordMapper.insert(walletRecord);
                //变更钱包主体
                //减未释放
                thisUnreleaseAmount = amount;
                //加冻结
                thisFrozenAmount = amount.multiply(negativeOne);;
                //增加区块链卡钱包的信息
                walletBlockService.generateRecord(null, memberId, amount, null, null, SundayCommonConstants.block_record_type_in, remark);
            /**
             * 区块链-退出-释放本金。加
             */
            }else if(type==SundayCommonConstants.wallet_record_type_quit_baseamount){
                 //2017年12月14日，删除推出区块链
                //本次释放的本金即为全部冻结金额
            /*    amount = wallet.getFrozenAmount();
                TianJieWalletRecord walletRecord = new TianJieWalletRecord(memberId, wallet.getId(), type, remark, wallet.getUnreleaseAmount(), amount, SundayCommonConstants.YES);
                walletRecordMapper.insert(walletRecord);
                //变更钱包主体
                //加未释放
                thisUnreleaseAmount = amount;
                //减冻结
                thisFrozenAmount = amount.multiply(negativeOne);;*/
                //生成释放计划
                 //2017年12月10日，在定时任务中创建
                 //如果退出区块链-退还本金。需要生成释放计划。8个月（32期）



            /**
             * 区块链-推出-释放收益。加
             */
            }else if(type==SundayCommonConstants.wallet_record_type_quit_profit) {
                //本次产生的收益=区块链可用金额-区块链本金
                TianJieWalletRecord walletRecord = new TianJieWalletRecord(memberId, wallet.getId(), type, remark, wallet.getUnreleaseAmount(), amount, SundayCommonConstants.YES);
                walletRecordMapper.insert(walletRecord);
                //变更钱包主体
                thisProfitAmount = amount;
             /**
              * 全球购消费
              */
            }else if(type==SundayCommonConstants.wallet_record_type_mall) {
                amount=amount.multiply(negativeOne);
                 //本次产生的收益=区块链可用金额-区块链本金
                 TianJieWalletRecord walletRecord = new TianJieWalletRecord(memberId, wallet.getId(), type, remark, wallet.getUnreleaseAmount(), amount, SundayCommonConstants.YES);
                 walletRecordMapper.insert(walletRecord);
                 //变更钱包主体
                 thisUnreleaseAmount = amount;
             }
            wallet.setTotalAmount(wallet.getTotalAmount().add(thisTotalAmount));
            wallet.setUnreleaseAmount(wallet.getUnreleaseAmount().add(thisUnreleaseAmount));
            wallet.setFrozenAmount(wallet.getFrozenAmount().add(thisFrozenAmount));
            //可提现的金额
            wallet.setReleaseAmount(wallet.getReleaseAmount().add(thisReleaseAmount));
            wallet.setCashAmount(wallet.getCashAmount().add(thisCashAmount));
            wallet.setProfitAmount(wallet.getProfitAmount().add(thisProfitAmount));
            super.update(wallet);


            return recordId;

    }

    /**
     * 组装DTO，
     * @param wallet
     * @param isCheckRevenue 是否查询实时收益
     * @return
     */
    public TianJieWalletDto packageDtoSingle(TianJieWallet wallet, Boolean isCheckRevenue){
        BigDecimal currentRevenue = new BigDecimal("0");
        BigDecimal ableCashAmount = wallet.getReleaseAmount().add(wallet.getCashAmount()).add(wallet.getProfitAmount());
        TianJieWalletDto dto = new TianJieWalletDto(wallet.getId(), wallet.getCreateTime(),wallet.getCreateDate(),
                wallet.getTotalAmount(),wallet.getUnreleaseAmount(),wallet.getFrozenAmount(),
                wallet.getReleaseAmount(),wallet.getCashAmount(),wallet.getProfitAmount(),
                ableCashAmount,wallet.getTotalAchievement(),wallet.getScale());
        return dto;
    }

    /**
     * 组装交易记录DTO
     * @return
     */
    public List<TianJieWalletRecordDto> packageRecordDtoMuilt(List<TianJieWalletRecord> records){
        List<TianJieWalletRecordDto> dtos = new ArrayList<>();
        for(TianJieWalletRecord record:records){
            dtos.add(new TianJieWalletRecordDto(record.getId(), record.getCreateTime(),record.getCreateDate(),
                     record.getType(),record.getRemark(),record.getAmount()));
        }
        return dtos;
    }
    /**
     * 组装充值产品DTO
     * @return
     */
    public List<TianJieWalletProductDto> packageProductDtoMuilt(List<TianJieWalletProduct> products){
        List<TianJieWalletProductDto> dtos = new ArrayList<>();
        for(TianJieWalletProduct product:products){
            dtos.add(new TianJieWalletProductDto(product.getId(), product.getCreateTime(),product.getCreateDate(),
                    product.getAmount(),  product.getType(),product.getGameAmount()));
        }
        return dtos;
    }
}
